import React, { memo, useEffect, useRef, useState } from 'react';
import {
  Form,
  Row,
  Col,
  Input,
  Button,
  DatePicker,
  Select,
  Textarea,
  Upload,
  MessagePlugin,
  Checkbox,
  Space,
} from 'tdesign-react';
import classnames from 'classnames';
import { SubmitContext, FormInstanceFunctions } from 'tdesign-react/es/form/type';
import CommonStyle from 'styles/common.module.less';
import Style from './index.module.less';
import { ITeacherInfo, getTeacherNames } from 'api/employee';
import { addCourse } from 'api/course/course';

const { FormItem } = Form;
const { Option } = Select;
const INITIAL_DATA = {
  name: '',
  type: '',
  payment: '',
  partyA: '',
  partyB: '',
  signDate: '',
  effectiveDate: '',
  endDate: '',
  remark: '',
  notary: '',
  file: [],
};

export default memo(() => {
  const date: any[] = [
    { name: '星期一' },
    { name: '星期二' },
    { name: '星期三' },
    { name: '星期四' },
    { name: '星期五' },
    { name: '星期六' },
    { name: '星期天' },
  ];

  const [teacherNames, setTeacherNames] = useState<ITeacherInfo[]>([]);

  useEffect(() => {
    getTeacherNames({ name: '教练' }).then((res) => {
      setTeacherNames(res.data);
    });
  }, []);

  const formRef = useRef<FormInstanceFunctions>();

  for (let i = 0; i < date.length; i++) {
    const [checked, setChecked] = useState(false);
    date[i] = { ...date[i], checked, setChecked };
  }

  const onSubmit = async (e: SubmitContext) => {
    if (e.validateResult === true) {
      const addValue = formRef.current?.getFieldsValue?.(true) as any;

      addValue.picture = addValue.picture.length !== 0 ? addValue.picture[0].response.name : '';
      addValue.courseTime = date.filter((v) => v.checked).map((v) => v.name);
      addValue.account = parseInt(addValue.account, 10);
      addValue.classTime = parseInt(addValue.classTime, 10);
      const res = await addCourse(addValue);
      if (res.data) {
        MessagePlugin.success(`添加${res.msg}`);
      } else {
        MessagePlugin.error(`添加${res.msg}`);
      }
      formRef?.current?.reset();
    }
  };

  const handleFail = ({ file }: { file: any }) => {
    console.error(`文件 ${file.name} 上传失败`);
  };

  return (
    <div className={classnames(CommonStyle.pageWithColor)}>
      <div className={Style.formContainer}>
        <Form ref={formRef} onSubmit={onSubmit} labelWidth={100} labelAlign='top'>
          <div className={Style.titleBox}>
            <div className={Style.titleText}>课程信息</div>
          </div>
          <Row gutter={[32, 24]}>
            <Col span={6}>
              <FormItem
                label='课程名称'
                name='name'
                rules={[{ required: true, message: '合程名称必填', type: 'error' }]}
              >
                <Input placeholder='请输入内容' />
              </FormItem>
            </Col>

            <Col span={6}>
              <FormItem
                label='课程类型'
                name='type'
                initialData={INITIAL_DATA.type}
                rules={[{ required: true, message: '课程类型必填', type: 'error' }]}
              >
                <Select placeholder='请选择类型'>
                  <Option key='A' label='游泳' value='游泳' />
                  <Option key='B' label='健身' value='健身' />
                  <Option key='C' label='康复' value='康复' />
                  <Option key='D' label='瑜伽' value='瑜伽' />
                </Select>
              </FormItem>
            </Col>

            <Col span={6}>
              <FormItem label='课程定价' name='price' rules={[{ required: true }]}>
                <Input placeholder='请输入金额' style={{ width: 160 }} />
              </FormItem>
            </Col>

            <Col span={3}>
              <FormItem label='课时' name='classTime' rules={[{ required: true }]}>
                <Input placeholder='请输入课时' style={{ width: 160 }} />
              </FormItem>
            </Col>

            <Col span={6}>
              <FormItem label='课程数量' name='account' initialData={INITIAL_DATA.partyB} rules={[{ required: true }]}>
                <Input placeholder={'请输入课程数量'}></Input>
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem label='授课老师' name='teacherId' rules={[{ required: true }]}>
                <Select placeholder='请选择老师'>
                  {teacherNames?.map((value, index) => (
                    <Option key={index} label={value.name} value={value.id}></Option>
                  ))}
                </Select>
              </FormItem>
            </Col>

            <Col span={6} className={Style.dateCol} rules={[{ required: true }]}>
              <FormItem label='开课日期' name='startTime'>
                <DatePicker mode='date' />
              </FormItem>
            </Col>
            <Col span={12} rules={[{ required: true }]}>
              <FormItem label='上课时间' name='courseTime'>
                <Space>
                  {date.map((value, index) => (
                    <Checkbox
                      key={index}
                      checked={value.checked}
                      onClick={() => {
                        value.setChecked(!value.checked);
                      }}
                    >
                      {value.name}
                    </Checkbox>
                  ))}
                </Space>
              </FormItem>
            </Col>
          </Row>

          <div className={Style.titleBox}>
            <div className={Style.titleText}>其他信息</div>
          </div>

          <FormItem label='课程描述' name='description' initialData={INITIAL_DATA.remark}>
            <Textarea placeholder='请输入课程描述' />
          </FormItem>

          <FormItem label='图片' name='picture'>
            <Upload
              action='http://127.0.0.1:5000/upload/avatar'
              theme='image'
              tips='请选择单张图片文件上传'
              accept='image/*'
            ></Upload>
          </FormItem>

          <FormItem>
            <Button type='submit' theme='primary'>
              提交
            </Button>
            <Button type='reset' style={{ marginLeft: 12 }}>
              重置
            </Button>
          </FormItem>
        </Form>
      </div>
    </div>
  );
});
